package com.wzl.thread.pool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 单线程化的线程池
 *
 *  创建只有一个线程的线程池测试
 *  该方法无参数，所有任务都保存队列LinkedBlockingQueue中，核心线程数为1，线程空闲时间为0
 *  等待唯一的单线程来执行任务，并保证所有任务按照指定顺序(FIFO或优先级)执行
 *
 * @author weizhongli
 * @since 2022-09-19 10:51
 */
@Slf4j
public class TcNewSingleThreadExecutor {

    /**
     * newSingleThreadExecutor方法
     */
    public static void NoFactoryPool(){
        //1.使用工厂类获取线程池对象
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        //2.提交任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.submit( () ->{
                log.info("线程执行啦.......哈哈哈哈哈哈" + finalI + "----" + Thread.currentThread().getName());
            });
        }
    }

    /**
     * newSingleThreadExecutor (ThreadFactory threadFactory)方法
     */
    public static void factoryPool(){
        //1.使用工厂类获取线程池对象
        ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
            int n = 1;
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"自定义的线程名称" + n++);
            }
        });
        //2.提交任务
        for (int i = 1; i <= 10; i++) {
            int finalI = i;
            executorService.submit( () ->{
                log.info("线程执行啦.......哈哈哈哈哈哈" + finalI + "----" + Thread.currentThread().getName());

            });
        }
    }
}